const db = require("../models");
const logger = require("../utils/_logger");
const DAO = require("../dao/DAO");
const Roles = db.models.roles;
const RoleMenus = db.models.roleMenus;



/** 新增|修改 */
function addOrUpdate(data, cb) {
    if (!data.name) return cb({ data: null, code: -1, message: "角色名称为空！" });
    let role = {
        name: data.name,
        code: data.code,
        status: data.status ?? true,
        remark: data.remark,
    }
    if (!data.id) { // 新增
        Roles.findOne({ where: { name: data.name } }).then(_ => {
            if (_ && _.id) return cb({ data: null, code: -1, message: "角色名称已存在！" });
            DAO.create(Roles, role, res => {
                cb(res)
            })
        })
    } else { // 修改
        DAO.update(Roles, role, { id: data.id }, res => {
            cb(res)
        })
    }
}


/** 新增 */
exports.create = async (req, res) => {
    const pm = req.body;
    addOrUpdate(pm, (data) => {
        res.sendResult(data)
    })
};
/** 更新 */
exports.update = (req, res) => {
    const pm = req.body;
    // 请求验证
    if (!pm.id) return res.sendResult({ data: '', code: -1, message: "ID不能为空！" })
    addOrUpdate(pm, (data) => {
        res.sendResult(data)
    })
};
/** 所有list */
exports.findAll = (req, res) => {
    let pm = {
        current_page: req.body?.current_page ?? 1,
        page_size: req.body?.page_size ?? 10,
        params: {
            name: req.body?.name ? { [db.Op.substring]: req.body?.name ?? '' } : '',
            code: req.body?.code ? { [db.Op.substring]: req.body?.code ?? '' } : '',
            status: req.body?.status??'',
        }
    }
    DAO.list(Roles, pm, list => {
        res.sendResult(list)
    })
};
/** 单个 */
exports.findOne = (req, res) => {
    const pm = req.body;
    DAO.findOne(Roles, pm, data => {
        res.sendResult(data)
    })
};


/** 删除 */
exports.delete = (req, res) => {
    const pm = req.body;
    // 请求验证
    if (!pm.id) return res.sendResult({ data: '', code: -1, message: "ID不能为空！" })
    DAO.delete(Roles, { id: pm.id }, data => {
        res.sendResult(data)
    })
};

/** 删除全部 */
exports.deleteAll = (req, res) => {
    const pm = req.body;
    DAO.deleteAll(Roles, data => {
        res.sendResult(data)
    })
};

/** 原始查询 */
exports.query = (req, res) => {
    const pm = req.body;
    let sql = 'SELECT * FROM `users`'
    DAO.doQuery(sql, data => {
        res.sendResult(data)
    })
};


/** 角色权限 */
exports.menus = (req, res) => {
    const pm = req.body;
    if (!pm.id) return res.sendResult({ data: '', code: -1, message: "ID不能为空！" })
    RoleMenus.findAll({ where: { role_id: pm.id }, raw: true, attributes: ['menu_id'] }).then(list => {
        res.sendResult({ data: list.map(i => i.menu_id), code: 0, message: "操作成功！" })
    })
};

/** 保存权限 */
exports.menusSave = async (req, res) => {
    const pm = req.body;
    if (!pm.id) return res.sendResult({ data: '', code: -1, message: "ID不能为空！" })
    const t = await db.sequelize.transaction();
    // 先删除角色权限
    try {
        await RoleMenus.destroy({ where: { role_id: pm.id }, transaction: t });
        await RoleMenus.bulkCreate(pm.value.map(item => {
            return { role_id: pm.id, menu_id: item }
        }), { transaction: t });
        await t.commit();
        res.sendResult({ data: '', code: 1, message: "保存成功" })
    } catch (err) {
        logger.errLog(err);
        t.rollback();
        res.sendResult({ data: '', code: -1, message: "当前网络不稳定，请稍后重试" })
    }

}

/** 获取简洁角色list */
exports.list = (req, res) => {
    DAO.listAll(Roles, { current_page: 0, attributes: ["id", "name"] }, list => {
        res.sendResult(list)
    })
}
